import { QuestionCircleFilled } from '@ant-design/icons';
import {
  Button,
  DatePicker,
  Drawer,
  Form,
  Input,
  InputNumber,
  message,
  Radio,
  Select,
  Switch,
  Tooltip,
} from 'antd';
import { FormInstance } from 'antd/es/form/Form';
import { SelectValue } from 'antd/lib/select';
import {
  FetchDataParam,
  FetchDataResponse,
  FetchRecordResponse,
  PageSelect,
} from 'components/UILibrary/pageSelect';
import { debounce } from 'lodash';
import moment from 'moment';
import { Moment } from 'moment';
import React, { ReactText } from 'react';
import { StrategyInfo, TaskStrategyInfo } from 'admin/schema/Strategy';
import {
  addTask,
  getMainNumList,
  getNumGroupList,
  getOnlineNotifyFlow,
  queryNotifyFlowById,
  getOnlineRobot,
  getSeatGroupList,
  getSoundTempListByType,
  getStrategyList,
  getTTSList,
  getTTSInfo,
  getVoiceRecognitionList,
} from 'admin/servers/servers';
import { clearNull, verifyNull } from 'utils/tools';
import { connect } from 'react-redux';
import { setAddTaskFormData } from '../../../../../store/root/action';
import { JSONObject } from '../../../../schema/common';
import AllowTimesList from './AllowTimesList';
import SelectDayTags from './SelectDayTags';
const { Option } = Select;

interface IProp {
  /**显示隐藏*/
  visible: boolean;
  /**回调函数，如果有参数，则需刷新列表页面 */
  callback: (fresh?: boolean) => any;
}

/**任务管理-创建任务state */
interface IState {
  /**选中的机器人id */
  currentRobotId: number | undefined;
  /**选中的通知流程id */
  currentNotifyFlowId: number | undefined;
  /**策略项-开关值：默认，关闭 */
  hasOpenCallback: boolean;
  /**执行时间段 */
  allowTimesArr: { start: string; end: string }[];
  /**策略项 */
  strategyArr: StrategyInfo[];
  /**提交数据loading */
  confirmLoading: boolean;
  /**外呼号码组-过滤时间范围 */
  timeType: string;
  /**任务执行时间:周期 */
  execTime: {
    type: 'daily' | 'weekly' | 'monthly';
    weeks?: number[];
    months?: number[];
  };
}
/** 任务管理-创建任务 */
class CallTaskOperation extends React.Component<IProp, IState> {
  /** 表单form */
  private formRef: React.RefObject<FormInstance>;
  /** 请选择机器人 */
  private robotRef: React.RefObject<any>;
  /** 请选择执行坐席组 */
  private seatsRef: React.RefObject<any>;
  /** 请选择语音识别厂商 */
  private voiceRef: React.RefObject<any>;
  /** 请选择TTS */
  private ttsRef: React.RefObject<any>;
  /** 请选择外呼号码组 */
  private calledGroupRef: React.RefObject<any>;
  /** 请选择主叫号码 */
  private callerRef: React.RefObject<any>;
  /** 请选择通知流程 */
  private notifyFlowRef: React.RefObject<any>;

  private strategyVal: TaskStrategyInfo[];

  /**时间格式 */
  private dateFormat: string;

  constructor(prop: IProp) {
    super(prop);

    this.formRef = React.createRef();
    this.robotRef = React.createRef();
    this.seatsRef = React.createRef();
    this.voiceRef = React.createRef();
    this.ttsRef = React.createRef();
    this.calledGroupRef = React.createRef();
    this.callerRef = React.createRef();
    this.notifyFlowRef = React.createRef();

    this.dateFormat = 'YYYY-MM-DD';
    this.strategyVal = [];

    this.state = {
      currentRobotId: undefined,
      currentNotifyFlowId: undefined,
      hasOpenCallback: false,
      allowTimesArr: [],
      strategyArr: [],
      confirmLoading: false,
      timeType: 'month',
      execTime: {
        type: 'daily',
        weeks: undefined,
        months: undefined,
      },
    };
  }

  componentDidMount() {
    const { addTaskFormData } = this.props as JSONObject; // 新建任务,表单缓存数据上屏
    const keylist = Object.keys(addTaskFormData);
    if (keylist.length > 0) {
      // 存在key=== flowType
      const last_flowType = keylist[keylist.length - 1]; //最后一次保存的数据
      const val = addTaskFormData[last_flowType];
      console.log('【新建任务】缓存历史数据========', last_flowType, val);
      if (val) {
        // 存在数据
        const newval: JSONObject = {
          flowType: val.flowType,
          robotId: val.workFlowId,
          notifyFlowId: val.workFlowId,
          maxSeatsSession: val.maxSeatsSession,
          maxCall: val.maxCall,
          soundType: val.soundType,
          blackSwitch: val.blackSwitch,
          taskDesc: val.taskDesc,
          strategyFlag: val.strategyFlag,
          callTimeInterval: val.callTimeInterval,
          allowTimesArr: val.allowTimes,
          execTime: val.execTime,
          skipHolidays: val.skipHolidays,
          startMode: val.startMode,
          callMode: val.callMode,
        };

        if (val.strategyValue) {
          newval.strategyValue = val.strategyValue;
          this.strategyVal = JSON.parse(val.strategyValue || '[]');
        }
        this.initStrategyList(this.strategyVal);
        this.setState(
          {
            currentRobotId: val.workFlowId,
            currentNotifyFlowId: val.workFlowId,
            hasOpenCallback: val.strategyFlag === 0,
            allowTimesArr: val.allowTimes,
            timeType: val.timeType,
          },
          () => {
            // 表单赋值
            this.formRef.current?.setFieldsValue(newval);
          }
        );

        setTimeout(() => {
          // 设置pageselect控件回显
          this.robotRef.current?.setValue(val.workFlowId);
          this.notifyFlowRef.current?.setValue(val.workFlowId);
          this.seatsRef.current?.setValue(val.seatsGroupId);
          // this.voiceRef.current?.setValue(val.mrcpId);
          this.ttsRef.current?.setValue(val.ttsId);
          this.calledGroupRef.current?.setValue(val.calledGroupId);
          this.callerRef.current?.setValue(val.callerId);
        }, 0);
      }
    } else {
      // 重呼策略-显示
      this.initStrategyList(null);
      this.setState({
        timeType: 'month',
        allowTimesArr: [
          {
            start: '9:00',
            end: '20:00',
          },
        ],
      });
    }
  }

  /**
   * 获取策略项列表数据
   * 默认展示值：strategyVal
   */
  private initStrategyList(strategyVal: TaskStrategyInfo[] | null) {
    getStrategyList({
      pageSize: 10000,
      pageNo: 1,
    })
      .then(res => {
        const list = res.data;
        for (const item of list) {
          item.initialValue = [];
          if (strategyVal) {
            const cur = strategyVal.find(i => i.strategyId === item.strategyOptionId);
            if (cur) {
              const l = [];
              if (cur.strategies && cur.strategies.length) {
                for (const b of cur.strategies) {
                  l.push(b.value);
                }
                item.initialValue = l;
              }
            }
          }
        }
        this.setState({
          strategyArr: list,
        });
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }

  /**
   * 重置抽屉
   */
  public reset(): void {
    this.formRef.current?.resetFields();
    this.setState({
      currentRobotId: undefined,
      currentNotifyFlowId: undefined,
      allowTimesArr: [],
      strategyArr: [],
      hasOpenCallback: false,
    });
  }

  /**
   * 关闭抽屉
   */
  close = () => {
    this.props.callback();
    this.reset();
  };

  /**
   * 查找机器人的dataProvider
   */
  private fetchRobot(args: FetchDataParam): FetchDataResponse {
    return new Promise(resolve => {
      getOnlineRobot(
        clearNull({
          pageNo: args.pageNum,
          pageSize: args.pageSize,
          robotName: args.keywords,
        })
      )
        .then(res => {
          resolve({
            data:
              res.data?.map(item => {
                return {
                  label: item.robotName,
                  value: item.robotId,
                };
              }) || [],
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }
  /**
   * 查找机器人的dataProvider
   */
  private fetchRobotRecord(robotId: string | number): FetchRecordResponse {
    return new Promise(resolve => {
      getOnlineRobot({
        pageNo: 1,
        pageSize: 1000,
      })
        .then(res => {
          // 根据id回显列表记录
          const item = (res.data || []).find(item => item.robotId === robotId);

          if (item) {
            resolve({
              label: item.robotName,
              value: item.robotId,
              data: item,
            });
          }
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }
  /**
   * 查找通知流程的dataProvider
   */
  private fetchNotifyFlow(args: FetchDataParam): FetchDataResponse {
    return new Promise(resolve => {
      getOnlineNotifyFlow(
        clearNull({
          pageNo: args.pageNum,
          pageSize: args.pageSize,
          robotName: args.keywords,
        })
      )
        .then(res => {
          resolve({
            data:
              res.data?.map(item => {
                return {
                  label: item.flowName,
                  value: item.notifyFlowId,
                };
              }) || [],
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }
  /**
   * 查找通知流程的dataProvider
   */
  private fetchNotifyFlowRecord(notifyFlowId: ReactText): FetchRecordResponse {
    return new Promise(resolve => {
      queryNotifyFlowById(notifyFlowId as number)
        .then(res => {
          const item = res.data || ({} as any);
          resolve({
            label: item.flowName,
            value: item.notifyFlowId,
            data: item,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }
  /**
   * 查找坐席组的dataProvider
   */
  private fetchSeatsGroup(args: FetchDataParam): FetchDataResponse {
    return new Promise(resolve => {
      getSeatGroupList(
        clearNull({
          pageNo: args.pageNum,
          pageSize: args.pageSize,
          condition: args.keywords,
        })
      )
        .then(res => {
          resolve({
            data:
              res.data?.map(item => {
                return {
                  label: item.seatGroupName,
                  value: item.seatGroupId,
                };
              }) || [],
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }
  /**
   * 查找坐席组的dataProvider
   */
  private fetchSeatsRecord(seatGroupId: string | number): FetchRecordResponse {
    return new Promise(resolve => {
      getSeatGroupList(
        clearNull({
          pageNo: 1,
          pageSize: 1000,
          condition: '',
        })
      )
        .then(res => {
          const item = (res.data || []).find(item => item.seatGroupId === seatGroupId);
          if (item) {
            resolve({
              label: item.seatGroupName,
              value: item.seatGroupId,
              data: item,
            });
          }
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }
  /**
   * 查找语音识别厂商的dataProvider
   */
  private fetchVoiceRec(args: FetchDataParam): FetchDataResponse {
    return new Promise(resolve => {
      getVoiceRecognitionList({
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        asrManufacturerName: args.keywords,
      })
        .then(res => {
          resolve({
            data: res.data?.map(item => {
              return {
                label: item.asrManufacturerName,
                value: item.asrManufacturerId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }
  /**
   * 查找语音识别厂商的dataProvider
   */
  private fetchVoiceRecord(mrcpId: ReactText): FetchRecordResponse {
    return new Promise(resolve => {
      getVoiceRecognitionList({
        pageNo: 1,
        pageSize: 1000,
      })
        .then(res => {
          const item = (res.data || []).find(item => item.asrManufacturerId === mrcpId);
          if (item) {
            resolve({
              label: item.asrManufacturerName,
              value: item.asrManufacturerId,
              data: item,
            });
          }
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  /**
   * 查找录音模板列表的dataProvider--根据机器人ID查询，默认最新版本
   */
  private fetchSoundListByType(args: FetchDataParam): FetchDataResponse {
    return new Promise((resolve, reject) => {
      // debugger;
      // 只有这2种任务有录音模板可选择：0-机器人任务；1-通知流程任务
      const flowType = this.formRef.current?.getFieldValue('flowType');
      const obj: any = {
        robotId: null,
        notifyFlowId: null,
        templateStatus: 1, // 查询录音模板状态：已完成
        pageNo: args.pageNum,
        pageSize: args.pageSize,
      };

      if (flowType === 1) {
        // 根据通知流程查找录音
        const notifyFlowId = this.state.currentNotifyFlowId;
        if (!notifyFlowId) {
          message.warning('当前通知流程选项为空，无法查询录音模板！');
          // 触发机器人验证
          this.formRef.current?.validateFields(['notifyFlowId']);
          reject('当前通知流程选项为空，无法查询录音模板！');
          return;
        }
        obj.notifyFlowId = notifyFlowId;
      } else {
        // 根据机器人流程查找录音
        const robotId = this.state.currentRobotId;
        if (!robotId) {
          message.warning('当前机器人选项为空，无法查询录音模板！');
          // 触发机器人验证
          this.formRef.current?.validateFields(['robotId']);
          reject('当前机器人选项为空，无法查询录音模板！');
          return;
        }
        obj.robotId = robotId;
      }
      getSoundTempListByType(flowType, clearNull(obj))
        .then(res => {
          resolve({
            data: res.data?.map(item => {
              return {
                label: item.templateName,
                value: item.templateId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  /**
   * 查找TTS厂商的dataProvider
   */
  private fetchTTS(args: FetchDataParam): FetchDataResponse {
    return new Promise(resolve => {
      getTTSList({
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        ttsManufacturerName: args.keywords,
      })
        .then(res => {
          resolve({
            data: res.data?.map(item => {
              return {
                label: item.ttsManufacturerName,
                value: item.ttsManufacturerId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }
  /**
   * 查找TTS厂商的dataProvider
   */
  private fetchTTSRecord(ttsId: ReactText): FetchRecordResponse {
    return new Promise(resolve => {
      getTTSInfo(ttsId as number)
        .then(res => {
          const item = res.data || ({} as any);
          resolve({
            label: item.ttsManufacturerName,
            value: item.ttsManufacturerId,
            data: item,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  /**
   * 查找主叫号码的dataProvider
   */
  private fetchMainNum(args: FetchDataParam): FetchDataResponse {
    return new Promise(resolve => {
      getMainNumList({
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        callingNumber: args.keywords,
      })
        .then(res => {
          resolve({
            data: res.data?.map(item => {
              return {
                label: item.callingNumber,
                value: item.callingId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }
  /**
   * 查找主叫号码的dataProvider
   */
  private fetchMainNumRecord(callingId: ReactText): FetchRecordResponse {
    return new Promise(resolve => {
      getMainNumList({
        pageNo: 1,
        pageSize: 10000,
        callingNumber: '',
      })
        .then(res => {
          const item = (res.data || []).find(item => item.callingId === callingId);
          if (item) {
            resolve({
              label: item.callingNumber,
              value: item.callingId,
              data: item,
            });
          }
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  /**
   * 查找外呼号码的dataProvider
   */
  private fetchNumGroup(args: FetchDataParam): FetchDataResponse {
    return new Promise(resolve => {
      const { timeType } = this.state;
      let start: string | undefined;
      let end: string | undefined;
      const { dateFormat } = this;
      // 今天
      const day = moment().format(dateFormat);
      switch (timeType) {
        case 'week':
          start = moment(day).subtract(1, 'weeks').format(dateFormat);
          end = day;
          break;
        case 'month':
          start = moment(day).subtract(1, 'months').format(dateFormat);
          end = day;
          break;
        case 'month_3':
          start = moment(day).subtract(3, 'months').format(dateFormat);
          end = day;
          break;
        default:
          start = undefined;
          end = undefined;
          break;
      }
      const params = {
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        callGroupName: args.keywords,
        beginTime: start,
        endTime: end,
      };
      console.log('号码组-请求参数：', params);
      getNumGroupList(clearNull(params))
        .then(res => {
          resolve({
            data: res.data?.map(item => {
              return {
                label: item.callGroupName,
                value: item.callGroupId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }
  /**
   * 查找外呼号码的dataProvider
   */
  private fetchNumGroupRecord(callGroupId: ReactText): FetchRecordResponse {
    return new Promise(resolve => {
      getNumGroupList({
        pageNo: 1,
        pageSize: 10000,
        callGroupName: '',
      })
        .then(res => {
          const item = (res.data || []).find(item => item.callGroupId === callGroupId);
          if (item) {
            resolve({
              label: item.callGroupName,
              value: item.callGroupId,
              data: item,
            });
          }
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  /**
   * 提交新建任务数据
   */
  private submitData() {
    const { dateFormat } = this;
    const form = this.formRef.current;
    form
      ?.validateFields()
      .then(async val => {
        const { allowTimesArr, timeType } = this.state;
        console.log(allowTimesArr, '选择的执行时间段');
        console.log(timeType, '选择的号码组时间范围');
        // 执行时间段-过滤格式不合法
        val.allowTimes = allowTimesArr.filter((item: any) => item && item.start && item.end);
        val.timeType = timeType;
        // 合并存储
        val.workFlowId = val.robotId || val.notifyFlowId; // 统一存储为流程id
        // 记录进缓存
        // debugger;
        const sessionObj = { ...val };
        console.log('写入缓存数据***', sessionObj);
        (this.props as JSONObject).setAddTaskFormData({
          [sessionObj.flowType]: sessionObj,
        });

        // 策略项是否开启
        if (this.state.hasOpenCallback) {
          // 开启
          val.strategyFlag = 0;
          const strategyValue = this.strategyVal.filter(item => {
            return item.strategies?.length;
          });
          // 策略项-JSON字符串
          if (strategyValue.length) {
            val.strategyValue = JSON.stringify(strategyValue);
          }
        } else {
          // 关闭
          // 人人任务或者人机协同任务，没有策略项，也是传1
          val.strategyFlag = 1;
          delete val.strategyValue;
        }

        // 语音识别厂商 写死
        val.mrcpId = 1;
        // 传给后端：修正字段格式
        val.skipHolidays = val.skipHolidays ? 'on' : 'off';
        val.blackSwitch = val.blackSwitch ? 1 : 0; // 黑名单：0-关
        val.dateBegin = val.dateBegin.format(dateFormat);
        val.expireDate = val.expireDate.format(dateFormat);
        // 传给后端：删除接口入参多余字段
        delete val.robotId;
        delete val.notifyFlowId;
        delete val.timeType;
        // debugger;
        console.log('创建任务-参数：', val);
        this.setState({
          confirmLoading: true,
        });
        try {
          const res = await addTask(clearNull(val));
          if (res.code === 0) {
            message.success('新增成功');
            this.props.callback(true);
            this.reset();
          }
        } catch (error) {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        }
        this.setState({
          confirmLoading: false,
        });
      })
      .catch(err => {
        message.error('请核对表单信息');
        console.log('表单提交：', err);
      });
  }

  /**
   * 新建任务日期限制
   */
  private disabledDate = (current: Moment) => {
    const checkDate = current && current.isSameOrBefore(moment());
    const { dateFormat } = this;
    if (current.format(dateFormat) === moment().format(dateFormat)) {
      return false;
    }
    return checkDate;
  };

  private buildFooter(): JSX.Element {
    return (
      <div className="drawer-footer-buttongroup">
        <Button
          type="primary"
          loading={this.state.confirmLoading}
          onClick={debounce(() => {
            this.submitData();
          }, 500)}
        >
          确定
        </Button>
        <Button onClick={this.close}>取消</Button>
      </div>
    );
  }

  private onStrategyChange(val: SelectValue, strategyInfo: StrategyInfo, index: number): void {
    const valArr: { key?: string; value?: string }[] = [];
    (val as string[]).forEach(item => {
      const aim = strategyInfo.values?.find(child => child.value === item);
      aim && valArr.push(aim);
    });
    this.strategyVal[index] = {
      strategyId: strategyInfo.strategyOptionId,
      strategyName: strategyInfo.strategyOptionName,
      referColumn: strategyInfo.referColumn,
      strategies: valArr,
    };
  }
  /**【外呼号码组】-入参-搜索时间范围改变 */
  changeTimeType = (e: any) => {
    const val = e.target.value;
    console.log(val, '选择的范围');
    this.formRef.current?.resetFields(['calledGroupId']);
    this.setState({ timeType: val });
  };

  render() {
    const { hasOpenCallback, strategyArr, timeType, allowTimesArr } = this.state;

    return (
      <Drawer
        key="task-add"
        className="task-operation-drawer"
        width={650}
        visible={this.props.visible}
        title="新建任务"
        onClose={this.close}
        footer={this.buildFooter()}
      >
        <Form
          layout="horizontal"
          ref={this.formRef}
          initialValues={{
            /**任务类型-对应流程类型: 0-机器人任务；1-通知流程任务；2-人机协同任务，默认0*/
            flowType: 0,
            /**音色类型: 默认0-TTS */
            soundType: 0,
            /**黑名单开关: 默认开启 */
            blackSwitch: true,
            /**开启日期: 默认今天*/
            dateBegin: moment(),
            /**过期日期: 默认今天+15天*/
            expireDate: moment().add(15, 'days'),
            /**执行周期 */
            execTime: { type: 'daily', weeks: [1, 2, 3, 4, 5], months: [1] },
            /**跳过节假日: 默认关闭 */
            skipHolidays: false,
            /**启动方式: 默认1-手动启动*/
            startMode: 1,
            /**呼叫模式: 默认0-预览式外呼*/
            callMode: 0,
          }}
        >
          <Form.Item
            label="任务名称"
            name="taskName"
            rules={verifyNull('请输入50位内字符')}
            getValueFromEvent={event => {
              return event.target.value.replace(/\s+/g, '');
            }}
          >
            <Input maxLength={50} placeholder="请输入50位内字符" allowClear />
          </Form.Item>
          <Form.Item label="任务类型" name="flowType" rules={verifyNull('请选择任务类型')}>
            <Select
              onChange={() => {
                // 类型变更时，重置变化区域表单值，保留通用字段，例如：启动日期等
                this.formRef.current?.resetFields([
                  'robotId',
                  'notifyFlowId',
                  'seatsGroupId',
                  'maxSeatsSession',
                  'maxCall',
                  // 'mrcpId',
                  'soundType',
                  'soundRecordTemplateId',
                  'ttsId',
                  'strategyFlag',
                  'callMode',
                ]);
                // 策略项-开关，恢复默认
                this.setState({ hasOpenCallback: false });
              }}
            >
              <Option value={0}>机器人任务</Option>
              <Option value={1}>通知流程任务</Option>
              {/* <Option value={2}>人机协同任务</Option>
              <Option value={3}>人工自动外呼任务</Option> */}
            </Select>
          </Form.Item>
          {/* 任务类型 */}
          {/* 选机器人：0-机器人任务、2-人机协同任务 */}
          {/* 选通知流程：1-通知流程任务 */}
          {/* 其他无 */}
          <Form.Item noStyle dependencies={['flowType']}>
            {({ getFieldValue }) => {
              const flowType = getFieldValue('flowType');
              return flowType === 0 || flowType === 2 ? (
                <Form.Item label="机器人" name="robotId" rules={verifyNull('请选择机器人')}>
                  <PageSelect
                    allowClear
                    ref={this.robotRef}
                    fetchData={this.fetchRobot}
                    fetchRecord={this.fetchRobotRecord}
                    placeholder="请选择机器人"
                    onChange={(val: any) => {
                      this.setState({
                        currentRobotId: val,
                      });
                    }}
                  />
                </Form.Item>
              ) : flowType === 1 ? (
                <Form.Item
                  label="通知流程"
                  name="notifyFlowId"
                  rules={verifyNull('请选择通知流程')}
                >
                  <PageSelect
                    allowClear
                    ref={this.notifyFlowRef}
                    fetchData={this.fetchNotifyFlow}
                    fetchRecord={this.fetchNotifyFlowRecord}
                    placeholder="请选择通知流程"
                    onChange={(val: any) => {
                      this.setState({
                        currentNotifyFlowId: val,
                      });
                    }}
                  />
                </Form.Item>
              ) : null;
            }}
          </Form.Item>
          {/* 坐席组：人机协同、人工自动外呼-相同，其他无 */}
          <Form.Item noStyle dependencies={['flowType']}>
            {({ getFieldValue }) => {
              const flowType = getFieldValue('flowType');
              return flowType === 2 || flowType === 3 ? (
                <Form.Item
                  label="执行坐席组"
                  name="seatsGroupId"
                  rules={verifyNull('请选择执行坐席组')}
                >
                  <PageSelect
                    allowClear
                    ref={this.seatsRef}
                    fetchData={this.fetchSeatsGroup}
                    fetchRecord={this.fetchSeatsRecord}
                    placeholder="请选择执行坐席组"
                  />
                </Form.Item>
              ) : null;
            }}
          </Form.Item>
          <Form.Item noStyle dependencies={['flowType']}>
            {({ getFieldValue }) => {
              const flowType = getFieldValue('flowType');
              return flowType === 3 ? (
                <Form.Item label="呼叫模式" required>
                  <Form.Item name="callMode" noStyle>
                    <Radio.Group>
                      <Radio value={0}>预览式外呼</Radio>
                      <Radio value={1}>预测式外呼</Radio>
                    </Radio.Group>
                  </Form.Item>
                  <Tooltip
                    overlayStyle={{ maxWidth: 270 }}
                    title={
                      <div>
                        <div style={{ marginBottom: 5 }}>
                          预览式外呼：预先给坐席分配外呼号码，但如果遇到空号、无法接通等情况，系统自动选择下一个号码继续呼叫，直到呼通为止。
                        </div>
                        <div>
                          预测式外呼：在满足呼损率的情况下，自动进行外呼，当呼通后才转接到坐席，由继续完成后面的工作。
                        </div>
                      </div>
                    }
                    className="tooltip-icon-blue"
                    arrowPointAtCenter
                    placement="bottomLeft"
                  >
                    <QuestionCircleFilled />
                  </Tooltip>
                </Form.Item>
              ) : null;
            }}
          </Form.Item>
          {/* 最大弹屏数：人机协同-仅有，其他无 */}
          <Form.Item noStyle dependencies={['flowType']}>
            {({ getFieldValue }) => {
              const flowType = getFieldValue('flowType');
              return flowType === 2 ? (
                <Form.Item
                  label="最大弹屏数"
                  initialValue={1}
                  name="maxSeatsSession"
                  rules={verifyNull('最大弹屏数不能为空')}
                >
                  <InputNumber min={1} max={5} precision={0} placeholder="请输入最大弹屏数" />
                </Form.Item>
              ) : null;
            }}
          </Form.Item>
          {/* 并发数：机器人、通知流程-相同，其他无 */}
          <Form.Item noStyle dependencies={['flowType']}>
            {({ getFieldValue }) => {
              const flowType = getFieldValue('flowType');
              return flowType === 0 || flowType === 1 ? (
                <Form.Item
                  initialValue={1}
                  label="并发数"
                  name="maxCall"
                  rules={verifyNull('并发数不能为空')}
                >
                  <InputNumber min={1} max={99999999} precision={0} placeholder="请输入并发数" />
                </Form.Item>
              ) : null;
            }}
          </Form.Item>
          {/* 语音识别厂商：机器人、人机协同-相同，其他无 */}
          {/* <Form.Item noStyle dependencies={['flowType']}>
            {({ getFieldValue }) => {
              const flowType = getFieldValue('flowType');
              return flowType === 0 || flowType === 2 ? (
                <Form.Item
                  label="语音识别厂商"
                  name="mrcpId"
                  rules={verifyNull('请选择语音识别厂商')}
                >
                  <PageSelect
                    allowClear
                    ref={this.voiceRef}
                    fetchData={this.fetchVoiceRec}
                    fetchRecord={this.fetchVoiceRecord}
                    placeholder="请选择语音识别厂商"
                  />
                </Form.Item>
              ) : null;
            }}
          </Form.Item> */}
          {/* 外呼语音：机器人、通知流程、人机协同-相同，其他无 */}
          <Form.Item noStyle dependencies={['flowType']}>
            {({ getFieldValue }) => {
              const flowType = getFieldValue('flowType');
              return flowType !== 3 ? (
                <Form.Item label="外呼语音" name="soundType" rules={verifyNull('请选择外呼语音')}>
                  <Radio.Group
                    onChange={() => {
                      // 清空form选择录音
                      this.formRef.current?.resetFields(['soundRecordTemplateId', 'ttsId']);
                    }}
                  >
                    <Radio value={0}>TTS</Radio>
                    <Radio value={1}>录音</Radio>
                  </Radio.Group>
                </Form.Item>
              ) : null;
            }}
          </Form.Item>
          {/* 录音：机器人，通知流程-相同，其他无*/}
          {/* 人机协同特殊：选择TTS需要选择模板，选择录音，不需要选择模板 */}
          <Form.Item noStyle dependencies={['flowType', 'soundType']}>
            {({ getFieldValue }) => {
              const flowType = getFieldValue('flowType');
              const soundType = getFieldValue('soundType');
              // 人工自动任务-无需展示
              if (flowType === 3) return null;
              // 非人工自动任务-继续以下逻辑
              if (soundType === 1) {
                // 选择录音方式-1
                if (flowType === 2) {
                  // 人机协同，不需要选择模板
                  return null;
                } else {
                  // 非人机协同任务，需要选择录音模板
                  return (
                    <Form.Item
                      label="录音"
                      name="soundRecordTemplateId"
                      rules={verifyNull('请选择录音模板')}
                    >
                      <PageSelect
                        allowClear
                        fetchData={this.fetchSoundListByType.bind(this)}
                        placeholder="请选择录音模板"
                      />
                    </Form.Item>
                  );
                }
              } else {
                // 选择TTS方式-0
                return (
                  <Form.Item label="TTS" name="ttsId" rules={verifyNull('请选择TTS')}>
                    <PageSelect
                      ref={this.ttsRef}
                      allowClear
                      fetchData={this.fetchTTS}
                      fetchRecord={this.fetchTTSRecord}
                      placeholder="请选择TTS"
                    />
                  </Form.Item>
                );
              }
            }}
          </Form.Item>
          {/* 3种任务-共有以下字段 */}
          <Radio.Group
            className="time-range-box"
            size="small"
            value={timeType}
            onChange={this.changeTimeType}
          >
            <Radio.Button value="all">全部</Radio.Button>
            <Radio.Button value="week">近一周</Radio.Button>
            <Radio.Button value="month">近一月</Radio.Button>
            <Radio.Button value="month_3">近三月</Radio.Button>
          </Radio.Group>
          <div className="calledGroup-box">
            <Form.Item
              className="a1"
              label="外呼号码组"
              name="calledGroupId"
              rules={verifyNull('请输入外呼号码组')}
            >
              <PageSelect
                ref={this.calledGroupRef}
                allowClear
                fetchData={this.fetchNumGroup.bind(this)}
                fetchRecord={this.fetchNumGroupRecord}
                placeholder="请选择外呼号码组"
              />
            </Form.Item>
            <Form.Item className="a2" label="黑名单" name="blackSwitch" valuePropName="checked">
              <Switch defaultChecked />
            </Form.Item>
          </div>
          <Form.Item label="主叫号码" name="callerId" rules={verifyNull('请选择主叫号码')}>
            <PageSelect
              ref={this.callerRef}
              allowClear
              fetchData={this.fetchMainNum}
              fetchRecord={this.fetchMainNumRecord}
              placeholder="请选择主叫号码"
            />
          </Form.Item>
          <Form.Item label="任务有效期" required className="date-range-box">
            <Form.Item name="dateBegin" rules={verifyNull('请选择开始日期')}>
              <DatePicker placeholder="请选择开始日期" disabledDate={this.disabledDate} />
            </Form.Item>
            <span className="split">-</span>
            <Form.Item name="expireDate" rules={verifyNull('请选择结束日期')}>
              <DatePicker placeholder="请选择结束日期" disabledDate={this.disabledDate} />
            </Form.Item>
          </Form.Item>
          <Form.Item label="执行时间" required>
            <SelectDayTags />
            <AllowTimesList
              timesArr={allowTimesArr}
              callback={(value: any) => {
                this.setState(
                  {
                    allowTimesArr: [...value],
                  },
                  () => {
                    console.log('执行时间段👌🏻****', this.state.allowTimesArr);
                  }
                );
              }}
            />
          </Form.Item>
          <Form.Item label="启动方式" name="startMode">
            <Radio.Group>
              <Radio value={1}>手动启动</Radio>
              <Radio value={0}>自动启动</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="任务描述" name="taskDesc">
            <Input maxLength={30} placeholder="请输入30位内字符" />
          </Form.Item>
          {/* 重呼策略：人机和人人外呼无重呼策略，其他有 */}
          <Form.Item noStyle dependencies={['flowType']}>
            {({ getFieldValue }) => {
              const flowType = getFieldValue('flowType');
              return flowType !== 2 && flowType !== 3 ? (
                <Form.Item label="重呼策略" name="strategyFlag">
                  <>
                    <Switch
                      className="strategy-switch"
                      checked={hasOpenCallback}
                      onChange={val => {
                        console.log(val, '重呼策略--值');
                        this.setState({ hasOpenCallback: val });
                      }}
                      disabled={!strategyArr.length}
                    />
                    {/* 没有策略项，需要给出提示文字 */}
                    {!strategyArr.length && (
                      <span className="tip">重呼策略需要配置策略项后才能使用</span>
                    )}
                  </>
                </Form.Item>
              ) : null;
            }}
          </Form.Item>
          {/* 开启策略项 */}
          {hasOpenCallback && (
            <>
              {strategyArr?.map((item, index) => {
                const option = item.values?.map(val => {
                  return {
                    label: val.key as string,
                    value: val.value as string,
                  };
                });
                return (
                  <Form.Item label={item.referName} key={index} rules={verifyNull('不能为空')}>
                    <Select
                      mode="multiple"
                      options={option}
                      maxTagPlaceholder=".."
                      maxTagCount={5}
                      defaultValue={item.initialValue}
                      onChange={val => {
                        this.onStrategyChange(val, item, index);
                      }}
                    />
                  </Form.Item>
                );
              })}
              <Form.Item label="外呼时间间隔" required>
                <Form.Item
                  name="callTimeInterval"
                  rules={verifyNull('请输入1-14400内的数字')}
                  noStyle
                >
                  <InputNumber
                    min={1}
                    max={14400}
                    precision={0}
                    style={{ width: 200 }}
                    placeholder="请输入1-14400内的数字"
                  />
                </Form.Item>
                <span style={{ marginLeft: 12 }}>分钟</span>
              </Form.Item>
            </>
          )}
        </Form>
      </Drawer>
    );
  }
}

// state 注入props
const mapStateToProps = (state: JSONObject) => {
  return {
    addTaskFormData: state.addTaskFormData,
  };
};
// action 注入props
const mapDispatchToProps = {
  setAddTaskFormData,
};
/**创建任务 */
export default connect(mapStateToProps, mapDispatchToProps, null, { forwardRef: true })(
  CallTaskOperation
);
